package com.imooc.miaosha.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.imooc.miaosha.domain.User;
import com.imooc.miaosha.redis.OrderKey;
import com.imooc.miaosha.redis.RedisService;
import com.imooc.miaosha.result.Result;
import com.imooc.miaosha.service.UserService;

@Controller
@RequestMapping("/miaosha")
public class TestController {
	
	@Autowired
	UserService userService;
	@Autowired
	RedisService redisServer;
	
	@RequestMapping("/json")
	@ResponseBody
	public Result json() {
		return  Result.success("success");
	}
	
	@RequestMapping("/test")
	public String test(Model model) {
		model.addAttribute("name", "qiushan");
		return "hello";
	}
	@RequestMapping("/db")
	@ResponseBody
	public Result db(@RequestParam(value = "UserId") Integer id) {
		User user = userService.getById(id);
		return  Result.success(user);
	}
	
	@RequestMapping("/tx")
	@ResponseBody
	@Transactional
	public Result tx(User user) {
		int result = userService.insertUser(user);
		user.setId(user.getId()-1);
		user.setName(user.getName()+" add xxx");
		result += userService.insertUser(user);
		userService.getById(user.getId()-1);
		return Result.success(result);
	}
	
	@RequestMapping("/redisSet")
	@ResponseBody
	public Result redisSet(@RequestParam(value = "key") String key,@RequestParam(value = "value") String str) {
		OrderKey orderKey = new OrderKey(0,"order");
		boolean result = redisServer.set(orderKey,key, str);
		return  Result.success(result);
	}
	
	@RequestMapping("/redisGet")
	@ResponseBody
	public Result redisGet(@RequestParam(value = "key") String key) {
		OrderKey orderKey = new OrderKey(0,"order");
		String result = redisServer.get(orderKey, key,String.class);
		return  Result.success(result);
	}

}
